package cn.appcentre.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 *
 * 进行上传下载的测试
 */
@Controller     //扫描
@RequestMapping("demoupload")
public class DownUploadController {
    /*
    文件下载不需要第三方jar包支持
     */
    @RequestMapping("/down")
    public ResponseEntity<byte[]> downTest() throws IOException {
        //下载时，响应头文件变为二进制的格式

        String path="D:/imgetest.png";   //path路径有中文时需要处理
        File file=new File(path);
        HttpHeaders httpHeaders=new HttpHeaders();
        httpHeaders.setContentDispositionFormData("attachment",path);  //告诉http头附件的位置
        httpHeaders.setContentType(MediaType.IMAGE_PNG);  //附件的类型
        //HttpStatus.CREATED  http是创建状态  import org.apache.commons.io.FileUtils;
        //FileUtils.readFileToByteArray(file)  二进制流读取到响应体
        return    new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),httpHeaders, HttpStatus.CREATED);
    }



    @RequestMapping("/upload")
    public String uploadTest(MultipartFile filetest, HttpServletRequest request) throws IOException {
        //如果上传是多个文件，则标为MultipartFile []数组

        //文件名字
        String  name=filetest.getOriginalFilename();
        File uploadF=new File("/"+name);  //上传的路径，根目录，可以根据后缀名判断上传的文件和设置对应的文件夹
        filetest.transferTo(uploadF);  //保存文件

        return "uploadTest";
    }

    @RequestMapping("/downuploadtest")
    public String downuploadtest12() {

        System.out.println("asd");
        return "downuploadtest";
    }
}
